<template>
  <div class="no-copy">
    <el-button class="fixed-button" type="primary" :icon="Check" @click="handleSave" :disabled="drawer"
      v-hasPermi="['vueflow:flow:edit']">
      保存
    </el-button>
    <!-- <el-dropdown placement="bottom" class="fixed-button" >
            <el-button type="primary" > 操作 </el-button>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item :icon="Plus" @click="handleAdd">新增</el-dropdown-item>
                    <el-dropdown-item :icon="Check" @click="handleSave" :disabled="drawer">保存</el-dropdown-item>
                </el-dropdown-menu>
            </template>
</el-dropdown> -->

    <!-- <el-button type="primary" class="fixed-button" @click="handleAdd">新增</el-button>
        <el-button type="primary" class="fixed-button" style="top: 80px;" @click="handleSave">保存</el-button> -->

    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <pane size="16">
          <el-scrollbar height="calc(100vh - 93px)">
            <div style="
              display: flex;
              justify-content: left;
              align-items: center;
              margin-top: 20px;
              margin-left: 10px;
            ">
              <el-icon style="color: #606266">
                <Tickets />
              </el-icon>
              <el-text style="font-size: 16px ;margin-left: 5px; font-weight: bold;">节点列表</el-text>
            </div>
            <div style="text-align: center;">
              <el-input v-model="rightTag.toolName" placeholder="工具搜索" style="margin-top: 10px; width: 90%"
                @input="handleSearch" />
            </div>

            <div style="padding: 5px">
              <!-- <ul>
                            <li v-for="(item, index) in filteredToolList" :key="index"
                                @click="handleAddNodeByTool(item)" @mouseover="handleMouseOver(index)"
                                @mouseout="handleMouseOut(index)" style="margin-bottom: 5px;   border-radius: 8px;"
                                :class="{ 'hovered': isHovered === index, 'clicked': isClicked === index }">
                                <img :src="getSrc(item.appIconPath)" alt="" style="height: 25px; width: 25px;">
                                {{ item.appName }}
                            </li>
                        </ul> -->

              <el-tree :data="rightTag.toolTreeList" :props="{ label: 'name', children: 'children' }" ref="treeRef"
                default-expand-all :filter-node-method="filterNode" @node-click="handleNodeClick">
                <template #default="{ node, data }">
                  <element-tree-line :node="node" :showLabelLine="false" :indent="16" :draggable="true"
                    @dragstart="onDragStart($event, 'Custom', data)">
                    <div v-if="data.type === 1" style="
                      display: flex;
                      justify-content: left;
                      align-items: center;
                    ">
                      <img :src="getSrc(data.appIconPath)" alt="" style="height: 14px; width: 14px" />
                      {{ data.appName }}
                    </div>

                    <div v-else style="
                      display: flex;
                      justify-content: left;
                      align-items: center;
                    ">
                      <img :src="listicon" alt="" style="height: 14px; width: 14px; color: '#1296db';" />{{ data.name }}
                    </div>

                  </element-tree-line>
                </template>
              </el-tree>
            </div>
          </el-scrollbar>
        </pane>
        <pane size="84">
          <div class="dnd-flow" @drop="onDrop">
            <VueFlow :nodes="nodes" :edges="edges" style="height: calc(100vh - 50px); width: 70vw"
              @node-click="logEvent('click', $event)" @connect="handleConnecting"
              @node-mouse-leave="logEvent('leave', $event)" :default-viewport="{ zoom: 1 }"
              @edge-double-click="logEvent('edge-dbClick', $event)" @edge-click="logEvent('edge-click', $event)"
              @contextmenu.capture="handleContextMenu" @dragover="onDragOver" @dragleave="onDragLeave"
              @pane-click="handleDrawerClose">
              <!-- 画布 -->
              <!-- <Background :style="{ background: '#f9fafd' }" /> -->
              <!-- 小地图 -->
              <!-- <MiniMap position="bottom-left" /> -->
              <!-- 控制器 -->
              <!-- <Controls position="bottom-center" /> -->

              <template #edge-custom="edgeProps">
                <CustomConnectionLine v-bind="edgeProps" @handleUpdateLabel="handleUpdateLabel" />
              </template>

              <template #node-Custom="nodeProps">
                <CustomNode v-bind="nodeProps" v-model:clickNodeId="clickNodeId" />
              </template>

              <DropzoneBackground :style="{
                backgroundColor: isDragOver ? '#e7f3ff' : 'transparent',
                transition: 'background-color 0.2s ease',
              }">
                <p v-if="isDragOver">拖拽到此处</p>
              </DropzoneBackground>
            </VueFlow>
          </div>
        </pane>
      </splitpanes>
    </el-row>

    <!-- <div v-if="rightTag.isMenuVisible" class="context-menu" @click.self="hideContextMenu"
            :style="rightTag.menuPosition" ref="excludeDiv">
            <el-segmented v-model="operateValue" :options="operateOptions" block />
            <el-scrollbar height="350">

                <div v-if="operateValue == '添加节点'" style="margin-top: 5px;">
                    <el-input v-model="rightTag.toolName" placeholder="工具名称" />
                    <ul>
                        <li v-for="(item, index) in filteredToolList" :key="index" @click="handleAddNodeByTool(item)">
                            <img :src="getSrc(item.appIconPath)" alt="" style="height: 25px; width: 25px;">
                            {{ item.appName }}
                        </li>
                    </ul>
                </div>

            </el-scrollbar>
        </div> -->

    <div v-if="drawer" class="pop-div" :class="{ 'pop-div-visible': drawer }">
      <div style="display: flex; justify-content: space-between; padding: 0">
        <div style="
            display: flex;
            justify-content: left;
            align-items: center;
            padding: 0;
            width: 50%;
          " v-if="showFlowData.data">
          <img v-if="showFlowData.data.icon" :src="getSrc(showFlowData.data.icon)" alt=""
            style="height: 25px; width: 25px" />
          <h1 style="
              overflow-wrap: break-word;
              word-break: break-word;
              font-size: 16px;
              font-weight: bold;
            ">
            {{ showFlowData.data.appName }}
          </h1>
        </div>
        <div style="display: flex; justify-content: space-between; padding: 0">
          <!-- <el-button link circle @click="handleCopy" title="复制" v-if="!showFlowData.source">
            <el-icon size="21">
              <CopyDocument />
            </el-icon>
          </el-button> -->
          <el-button link circle @click="handleDeleteNode" title="删除" v-if="!showFlowData.source">
            <el-icon size="21">
              <Delete />
            </el-icon>
          </el-button>
          <el-button link circle @click="handleDeleteEdge" title="删除" v-if="showFlowData.source">
            <el-icon size="21">
              <Delete />
            </el-icon>
          </el-button>
          <el-button link circle @click="handleDrawerClose" title="关闭">
            <el-icon size="21">
              <Close />
            </el-icon>
          </el-button>
        </div>
      </div>

      <el-scrollbar style="position: relative; height: calc(100vh - 270px)">
        <node-pop :showFlowData="showFlowData" :drawer="drawer" :recapture="recapture"
          :inputSelectNodeIds="inputSelectNodeIds" v-if="showFlowData.data"></node-pop>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { markRaw, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { Panel, VueFlow, useVueFlow } from "@vue-flow/core";
import { Background } from "@vue-flow/background"; // 背景
import { Controls } from "@vue-flow/controls"; //控制(自带的缩放、居中、加锁功能)
import { MiniMap } from "@vue-flow/minimap"; //缩略图
import { NodeToolbar } from "@vue-flow/node-toolbar";
import CustomNode from "./components/CustomNode.vue";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import useAppStore from '@/store/modules/app'
import {
  addFlow,
  getToolCategoryTree,
  updateFlow,
} from "../../../api/flow/flow";
import {
  ArrowDown,
  Right,
  CircleCheckFilled,
  Check,
  CirclePlusFilled,
  Plus,
  Close,
  Delete,
} from "@element-plus/icons-vue";
import { listAllApp } from "@/api/flow/appApi";
import NodePop from "./NodePop/index.vue";
import flowNodesStore from "@/store/modules/flowNodes";
import { get } from "@vueuse/core";
import { getElementLabelLine } from "element-tree-line";
import "@/assets/styles/vueflow.scss";
import DropzoneBackground from "./components/DropzoneBackground.vue";
import CustomConnectionLine from "./components/CustomConnectionLine.vue";
import { ElDialog, ElIcon, ElMessageBox, ElNotification } from "element-plus";
import { ChromeFilled } from '@element-plus/icons-vue';
import { getIsCustomLine, getLineMethodName } from "./utils/lineMethodName";
import listicon from "@/assets/images/listicon.svg";
const { addNodes, screenToFlowCoordinate, onNodesInitialized, updateNode } =
  useVueFlow();
const ElementTreeLine = getElementLabelLine(h);
const flowNodes = flowNodesStore();
const appStore = useAppStore()
const route = useRoute();
const router = useRouter();
const props = defineProps({
  flowData: {
    type: Object,
  },
  switchActiveIndex: {
    type: Function,
  },
  getHandleGetList: {
    type: Function,
  },
  contrast_node_string: {
    type: String,
  }
});

const emits = defineEmits(["contrast_node_string"]);
const state = {
  draggedType: ref(null),
  draggedData: ref(null),
  isDragOver: ref(false),
  isDragging: ref(false),
};
const { draggedType, draggedData, isDragOver, isDragging } = state;
// 定义标志位，用于记录连线操作是否正在进行
const isConnecting = ref(false);

const showFlowData = ref({});
const { proxy } = getCurrentInstance();
const drawer = ref(false);
const recapture = ref(null);
const inputSelectNodeIds = ref([]);
const form = ref({
  data: {
    label: null,
  },
});
const rightTag = ref({
  isMenuVisible: false,
  menuPosition: { top: 0, left: 0 },
  toolList: [],
  toolName: null,
  toolTreeList: [],
});

const filteredToolList = computed(() => {
  if (!rightTag.value.toolName) {
    return rightTag.value.toolList;
  }
  const searchTerm = rightTag.value.toolName.toLowerCase();
  return rightTag.value.toolList.filter((item) =>
    item.appName.toLowerCase().includes(searchTerm)
  );
});
const treeRef = ref(null);

const handleSearch = () => {
  treeRef.value.filter(rightTag.value.toolName);
};
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.includes(value);
};
const dataId = ref(null);
const clickNodeId = ref(null);

const operateValue = ref("添加节点");
const operateOptions = ["添加节点", "Tue"];

onMounted(() => {
  if (props.flowData.id) {
    dataId.value = props.flowData.id;
    nodes.value = JSON.parse(props.flowData.nodes);
    edges.value = JSON.parse(props.flowData.edges);
  } else {
    flowNodes.setFlowNodes([]);
  }
  getList();
  document.addEventListener("click", handleClickOutside);

  document.addEventListener("keydown", onKeyDown);
});
onUnmounted(() => {
  document.removeEventListener("click", handleClickOutside);
  document.removeEventListener("keydown", onKeyDown);
});

const getList = () => {
  listAllApp().then((res) => {
    rightTag.value.toolList = res.data;
  });

  getToolCategoryTree().then((res) => {
    rightTag.value.toolTreeList = res.data;
  });
};

const nodes = ref([
  // an input node, specified by using `type: 'input'`
  // {
  //     id: "1",
  //     type: "input",
  //     position: { x: 100, y: 100 },
  //     data: { label: "Node 1" },
  //     sourcePosition: 'right', // 输出点在右侧
  //     targetPosition: 'left'   // 输入点在左侧
  // },
  // {
  //     id: "2",
  //     position: { x: 300, y: 100 },
  //     data: { label: "Node 2" },
  //     sourcePosition: 'right', // 输出点在右侧
  //     targetPosition: 'left'   // 输入点在左侧
  // },
  // {
  //     id: "3",
  //     type: "output",
  //     position: { x: 500, y: 100 },
  //     data: { label: "Node 3", data: { hello: "world" } },
  //     sourcePosition: 'right', // 输出点在右侧
  //     targetPosition: 'left'   // 输入点在左侧
  // },
  // {
  //     id: "4",
  //     type: 'Custom', // <-- this is the custom node type name
  //     position: { x: 500, y: 200 },
  //     data: {
  //         label: "Node 4",
  //         hello: "world",
  //         icon: "Odometer",
  //     },
  // },
]);

const edges = ref([
  // {
  //     id: "e1->2",
  //     source: "1",
  //     target: "2",
  //     markerEnd: { type: 'arrowclosed' } // 添加箭头标记
  // },
  // {
  //     id: "e2->3",
  //     source: "2",
  //     target: "3",
  //     animated: true,
  // },
  // {
  //     id: "e2->4",
  //     source: "2",
  //     target: "4",
  //     data: {
  //         hello: "world",
  //     },
  //     markerEnd: { type: 'arrowclosed' } // 添加箭头标记
  // },
]);

// const edgeTypes = {
//   Custom: markRaw(CustomConnectionLine),
// };
// const nodeTypes = {
//   // 将节点类型名称映射到组件定义/名称的对象
//   Custom: markRaw(CustomNode),
// };

const logEvent = (eventName, event) => {
  if (eventName === "click") {
    restClick();
    const { node } = event;
    console.log('nodeId', node.id);
    clickNodeId.value = node.id;
    showFlowData.value = node;

    // 根据节点的id 去edges里面找 在他前面的并且node.data.type为1的所有node,一直往前找，直到找到第一个node
    inputSelectNodeIds.value = getSelectListByNodeID(node.id);
    recapture.value = !recapture.value;
    drawer.value = true;
  }

  if (eventName === "leave") {
    const { node } = event;
    nodes.value = nodes.value.map((n) => {
      if (n.id === node.id) {
        return {
          ...n,
          position: {
            x: node.position.x,
            y: node.position.y,
          },
        };
      }
      return n;
    });
    flowNodes.setFlowNodes(nodes.value);
  }

  if (eventName === "edge-dbClick") {
    const { edge } = event;
    nodes.value.forEach((item) => {
      if (item.id == edge.sourceNode.id) {
        if (item.data.nextEdges) {
          item.data.nextEdges.forEach((edgeItem, index) => {
            if (edgeItem.edgeId == edge.id) {
              item.data.nextEdges.splice(index, 1);
              item.data.nextList.splice(index, 1);
            }
          })
        }
      }
    });

    handleDrawerClose();
    nextTick(() => {
      flowNodes.setFlowNodes(nodes.value, 2);
    })
    edges.value = edges.value.filter((e) => e.id !== edge.id);
  }

  if (eventName === "edge-click") {
    restClick();
    const { edge } = event;
    showFlowData.value = edge;
    showFlowData.value.data.appName = edge.sourceNode.data.label + '-' + edge.targetNode.data.label;
    recapture.value = !recapture.value;
    drawer.value = true;
  }
};

const restClick = () => {
  showFlowData.value = null;
  isClicked.value = null;
  isHovered.value = null;
  clickNodeId.value = null;
}

const handleContextMenu = (event) => {
  const { node } = event;

  const isNode = event.target.closest(".vue-flow__node");
  if (!isNode) {
    // 阻止默认的右键菜单
    event.preventDefault();

    // 更新菜单的位置
    rightTag.value.menuPosition = {
      top: event.clientY - 50 + "px",
      left: event.clientX + "px",
    };

    rightTag.value.isMenuVisible = true;
  }
};

const handleDeleteNode = () => {
  proxy.$modal
    .confirm("是否确认删除此节点？")
    .then(function () {
      console.log(nodes.value, showFlowData.value);

      nodes.value = nodes.value.filter((n) => n.id !== showFlowData.value.id);

      // 过滤掉与要删除节点相关的边
      const nodeIdToDelete = showFlowData.value.id;

      let sourceEdges = edges.value.filter(edge => edge.target === nodeIdToDelete)

      sourceEdges.forEach(edge => {
        let sourceNode = nodes.value.find(node => node.id === edge.source);
        if (sourceNode && sourceNode.data.nextList.length > 0) {
          // 倒序遍历 nextList，避免删除元素后索引混乱
          for (let i = sourceNode.data.nextList.length - 1; i >= 0; i--) {
            let item = sourceNode.data.nextList[i];
            if (item.nextId === nodeIdToDelete) {
              // 删除该节点
              sourceNode.data.nextList.splice(i, 1);
              sourceNode.data.nextEdges.splice(i, 1);
            }
          }
        }

      });

      edges.value = edges.value.filter((edge) => {
        return edge.source !== nodeIdToDelete && edge.target !== nodeIdToDelete;
      });
    })
    .then(() => {
      flowNodes.setFlowNodes(nodes.value);
      handleDrawerClose();
    })
    .catch(() => { });
};

const handleCopy = () => {
  let need_copy_node = JSON.parse(JSON.stringify(showFlowData.value));
  need_copy_node.data.id = Date.now().toString();
  need_copy_node.data.label = need_copy_node.data.label + '(复制)';
  let copy_node = {
    id: need_copy_node.data.id,
    data: need_copy_node.data,
    position: { x: need_copy_node.position.x + 50, y: need_copy_node.position.y + 100 },
    type: need_copy_node.type
  }
  nodes.value.push(copy_node);
}

const handleDeleteEdge = () => {
  proxy.$modal
    .confirm("是否确认删除此链接线？")
    .then(function () {
      const edge = showFlowData.value;
      nodes.value.forEach((item) => {
        if (item.id == edge.sourceNode.id) {
          if (item.data.nextEdges) {
            item.data.nextEdges.forEach((edgeItem, index) => {
              if (edgeItem.edgeId == edge.id) {
                item.data.nextEdges.splice(index, 1);
                item.data.nextList.splice(index, 1);
              }
            })
          }
        }
      });

      handleDrawerClose();
      nextTick(() => {
        flowNodes.setFlowNodes(nodes.value, 2);
      })
      edges.value = edges.value.filter((e) => e.id !== edge.id);
    })
};

const handleDrawerClose = (flag = 0) => {
  if (isConnecting.value) {
    return;
  }
  drawer.value = false;
  showFlowData.value = {};
  clickNodeId.value = null;
};

const handleConnecting = (event) => {
  if (event.source === event.target) {
    // 阻止连接自己
    return false;
  }

  let source_node = flowNodes.getFlowNodes().find(node => node.id == event.source);
  let target_node = flowNodes.getFlowNodes().find(node => node.id == event.target);

  // 如果起始点的methodName是end，则不允许连接； 如果结束点的methodName是start，则不允许连接
  if (source_node.data.methodName == 'end' || target_node.data.methodName == 'start') {
    return false;
  }

  let edge = {
    id: `e!${event.source}-${event.target}`,
    source: event.source,
    target: event.target,
    sourceNode: source_node,
    targetNode: target_node,
    type: 'custom',
    // markerEnd: { type: "arrowclosed" },
    data: { label: '', }
  }

  edge.data.methodName = getLineMethodName(source_node.data.positionFlag);

  edges.value.push(edge);

  nextTick(() => {
    handleDrawerClose();
    isConnecting.value = true;
    logEvent("edge-click", { edge });
    setTimeout(() => {
      isConnecting.value = false;
    }, 1000);
  });
};

let handleClickOutside = (event) => {
  // 点击外部时隐藏菜单
  if (rightTag.value.isMenuVisible) {
    const excludeDiv = proxy.$refs.excludeDiv;
    if (!excludeDiv || !excludeDiv.contains(event.target)) {
      rightTag.value.isMenuVisible = false;
    }
  }
};


const handleSave = () => {

  let flowNodeList = flowNodes.getFlowNodes();
  // flowNodeList.forEach((element) => {
  //   let findEdges = edges.value.filter((item) => item.source == element.id);
  //   if (findEdges.length > 0) {
  //     element.data.nextId = findEdges[findEdges.length - 1].target;
  //   }
  // });

  let dataForm = {
    id: null,
    name: null,
    nodes: JSON.stringify(flowNodeList),
    edges: JSON.stringify(edges.value),
  };


  if (dataId.value) {
    dataForm.id = dataId.value;
    handlePrompt(dataForm, (form) => updateFlow(form).then(res => {
      if (res.code == 200) {
        emits("update:flowData", form)
        proxy.$modal.msgSuccess("修改成功");
        props.getHandleGetList();
        emits("update:contrast_node_string", JSON.stringify(flowNodeList))
      }
    }));
  } else {
    handlePrompt(dataForm, (form) => addFlow(form).then(res => {
      if (res.code == 200) {
        emits("update:flowData", res.data)
        dataId.value = res.data.id;
        proxy.$modal.msgSuccess("保存成功");
        props.getHandleGetList();
        emits("update:contrast_node_string", JSON.stringify(flowNodeList))
      }
    }));
  }

  function handlePrompt(form, apiCall) {
    proxy.$prompt("请输入名称", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: props.flowData.name, // 默认值
    })
      .then(({ value }) => {
        // 检查 value 是否为空
        if (!value || value.trim() === '') {
          proxy.$modal.msgError('名称不能为空，请重新输入');
          return;
        } else {
          form.name = value;
          return apiCall(form);
        }
      })
  }
};

//暴露handleSave方法
defineExpose({
  handleSave,
})

const isHovered = ref(-1);
const isClicked = ref(-1);

const handleMouseOver = (index) => {
  isHovered.value = index;
};

const handleMouseOut = () => {
  isHovered.value = -1;
};
const handleAddNodeByTool = (
  item,
  id = Date.now().toString(),
  position = { x: 200, y: 200 }
) => {
  if (!item) return;
  let flowNodeList = flowNodes.getFlowNodes();
  let findNodes = flowNodeList.filter(obj => obj.data.methodName == item.methodName);

  let label = item.appName;
  let maxNum = 0;

  if (findNodes.length > 0) {
    findNodes.forEach(obj => {
      // 根据'-'分割名称，获取下标为1的数据整数化，并+1
      let num = parseInt(obj.data.label.split('-')[obj.data.label.split('-').length - 1]);
      if (num > maxNum) {
        maxNum = num;
      }
    });
    label = item.appName + '-' + (maxNum + 1);
  } else {
    label = item.appName + '-1';
  }

  if (item.methodName == 'start' || item.methodName == 'end') {
    if (maxNum >= 1) {
      proxy.$message.error('请勿重复添加开始和结束节点！');
      return;
    }
  }

  nodes.value.push({
    id: id,
    type: "Custom",
    position: position,
    data: {
      id: id,
      label: label,
      desc: item.appDescribe,
      icon: item.appIconPath,
      appName: item.appName,
      appNameEn: item.appNameEn,
      methodName: item.methodName,
      positionFlag: item.positionFlag,
      nextList: [],
      nextEdges: [],
      data: {
        positionFlag: item.positionFlag,
        methodName: item.methodName,
        type: "",
        standartName: "",
        sheetSize: "",
        sheetOrientation: "",
        projectionMethod: "",
        input3DData: "",
        input2DData: "",
        sheetName: "",
        projectFun: "",
        projectLineName: "",
        views: "",
        scale: "",
        componetFile: "",
        componetName: "",
        titles: [
          {
            valueFrom: "",
            findType: "",
            findValue: "",
          },
        ],
        step: "",
        lineType: "",
        lineWidth: "",
        lineColor: "",
        frontName: "",
        frontSize: "",
        Pos: "",
        titleFrontName: "",
        titleFrontSize: "",
        columns: [
          {
            title: "",
            width: "",
            value: "",
          },
        ],
        view: "",
        dir: "",
        viewName: "",
        fatherView: "",
        pos3D: "",
        radiu: "",
        type: "",
        points: "",
        property: [
          {
            type: "",
            name: "",
          },
        ],
      },
    },
  });

  flowNodes.setFlowNodes(nodes.value, 1);
  rightTag.value.isMenuVisible = false;
};

const hideContextMenu = () => {
  rightTag.value.isMenuVisible = false;
};
let getSrc = function (url) {
  return import.meta.env.VITE_APP_BASE_API + url + "?version=" + Date.now();
};

const getSelectListByNodeID = (nodeID, previousNodes = []) => {
  let edge_list = edges.value.filter((element) => element.target === nodeID);
  if (edge_list.length > 0) {
    edge_list.forEach((edge) => {
      if (previousNodes.indexOf(edge.source) === -1) {
        previousNodes.push(edge.source);
        getSelectListByNodeID(edge.source, previousNodes);
      }
    });
  }
  return previousNodes;
};

// 根据前面的节点id数组，去过滤出所有的type==2的节点
const getNodesByNodeIds = (nodeIds) => {
  let nodeList = flowNodes.getFlowNodes();
  const resultList = nodeList.filter((node) => nodeIds.includes(node.id));
  return resultList;
};

const handleNodeClick = (data, node) => {
  if (data.type !== 1) {
    return;
  }
  ElNotification({
    title: data.name,
    message: data.appDescribe,
    duration: 2500,
    icon: () => {
      return h('img', {
        src: getSrc(data.appIconPath),
        alt: '',
        style: 'height: 25px; width: 25px'
      });
    },
  })
};

function onDragStart(event, type, data) {
  if (data.type !== 1) {
    event.preventDefault();
    return false;
  }

  if (event.dataTransfer) {
    event.dataTransfer.setData("application/vueflow", type);
    event.dataTransfer.effectAllowed = "move";
  }
  draggedData.value = data;
  draggedType.value = type;
  isDragging.value = true;
  document.addEventListener("drop", onDragEnd);
}

function onDragEnd() {
  isDragging.value = false;
  isDragOver.value = false;
  draggedData.value = null;
  draggedType.value = null;
  document.removeEventListener("drop", onDragEnd);
}

watch(isDragging, (dragging) => {
  document.body.style.userSelect = dragging ? "none" : "";
});

function onDragOver(event) {
  event.preventDefault();
  if (draggedType.value) {
    isDragOver.value = true;
    if (event.dataTransfer) {
      event.dataTransfer.dropEffect = "move";
    }
  }
}

function onDragLeave(event) {
  isDragOver.value = false;
}

function onDrop(event) {
  const position = screenToFlowCoordinate({
    x: event.clientX,
    y: event.clientY,
  });
  let nodeId = Date.now().toString();
  handleAddNodeByTool(draggedData.value, nodeId, position);
  const { off } = onNodesInitialized(() => {
    updateNode(nodeId, (node) => ({
      position: {
        x: node.position.x - node.dimensions.width / 2,
        y: node.position.y - node.dimensions.height / 2,
      },
    }));

    off();
  });
}

function onKeyDown(event) {
  if (Object.keys(showFlowData.value).length === 0) {
    return;
  }

  if (event.key === 'Delete') {

    if (showFlowData.value.source) {
      handleDeleteEdge();
    } else {
      handleDeleteNode();
    }
  }
}

function handleUpdateLabel(edgeId) {
  proxy.$prompt('请输入新值', "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    context: '123' // 设置输入框的默认值为 123,
  }).then(({ value }) => {
    let find_edge = edges.value.find(item => item.id === edgeId)
    find_edge.data.label = value;
  }).catch(() => { });
}
</script>

<style lang="scss" scoped>
.fixed-button {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 1001;
  /* 设置较高的层级，确保按钮在其他元素之上 */
}

.context-menu {
  margin: 0;
  background: #fff;
  position: absolute;
  background-color: white;
  border: 1px solid #ccc;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
  z-index: 1000;
  list-style-type: none;
  padding: 5px;
  border-radius: 8px;
  font-size: 14px;
  color: #333;
}

.context-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.context-menu li {
  padding: 7px 16px;
  cursor: pointer;
}

.context-menu li:hover {
  background-color: #eee;
}

.pop-div {
  position: fixed;
  height: calc(100vh - 150px);
  width: 400px;
  background-color: #ffffff;
  top: 100px;
  right: -400px;
  padding: 10px;
  /* 初始位置在屏幕右侧外面 */
  border-top-left-radius: 10px;
  border-bottom-left-radius: 10px;

  transition: right 0.3s ease;
  z-index: 1000;

  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1), 0 4px 8px rgba(0, 0, 0, 0.15),
    0 8px 16px rgba(0, 0, 0, 0.2);
}

.pop-div-visible {
  right: 0;
  /* 显示时移动到屏幕右侧边缘 */
}

.el-segmented {
  --el-segmented-item-selected-color: var(--el-text-color-primary);
  --el-segmented-item-selected-bg-color: #409eff;
  --el-border-radius-base: 16px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  padding: 3px;
  cursor: pointer;
  color: #409eff;
  display: flex;
  align-content: center;
}

.hovered {
  background-color: #e0e0e0;
  /* 鼠标悬停时的背景颜色 */
}

.clicked {
  background-color: #b0e0e6;
  /* 点击时的背景颜色 */
}

/* 使用深度选择器让样式穿透到子组件 */
/* 修改垂直虚线为黑色 */
:deep(.element-tree-node-line-ver) {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  border-left: 1px dashed #000;
  /* 改为纯黑色 */
}

/* 修改水平虚线为黑色 */
:deep(.element-tree-node-line-hor) {
  display: block;
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  border-top: 1px dashed #000;
  /* 改为纯黑色 */
}

/* 修改展开图标的虚线为黑色 */
:deep(.el-tree-node__expand-icon) {
  &::before {
    border-left: 1px dashed #000 !important;
    /* 改为纯黑色 */
  }
}

/* 确保内容区域有相对定位 */
:deep(.el-tree .el-tree-node__content) {
  position: relative;
}

/* 如果需要，也可以覆盖节点的默认虚线 */
:deep(.el-tree-node:before) {
  border-left: 1px dashed #000 !important;
}

:deep(.el-tree-node:after) {
  border-top: 1px dashed #000 !important;
}

.no-copy {
  user-select: none;
  /* 禁止选中 */
  -webkit-user-select: none;
  /* 兼容旧版浏览器 */
  -moz-user-select: none;
  -ms-user-select: none;
}

.with-divider {
  position: relative;
  padding: 0 0 0 10px !important;
}

.with-divider::after {
  content: "";
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 1px;
  background-color: #dcdfe6;
  /* 分割线颜色，可根据需要调整 */
}
</style>
